<template>
  <vue-editor ref="editor" v-model="content" :editor-options="editorSettings" :editor-toolbar="toolbar" @focus="focus" @blur="blur" @text-change="textChange" @selection-change="selection" />
</template>
<script>
import axios from 'axios'

// import { ImageDrop } from 'quill-image-drop-module'
import ImageResize from 'quill-image-resize-module'

import { dataURLtoFile, compressedImg } from './_imgHandle.js'

// Quill.register('modules/imageDrop', ImageDrop);
// window.Quill.register('modules/imageResize', ImageResize);

export default {
  name: 'ui-editor',
  props: {
    toolbar: {
      type: Array,
      default() {
        return [
          ['bold', 'italic', 'underline'],
          [{ list: 'ordered' }, { list: 'bullet' }],
          ['image', 'code-block']
        ]
      }
    },
    value: {
      type: String
    },
    ajax: {
      type: String
    }
  },
  data() {
    return {
      base64: '',
      editor: null,
      cursorLocation: null,
      imgLocation: null,
      editorSettings: {
        modules: {
          // imageDrop: false,
          imageResize: {
            modules: ['Resize']
          }
        }
      },
      lock: false,
      reader: null,
      image: null
    }
  },
  computed: {
    content: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  methods: {
    focus(Editor) {
      // console.log('index', this.editor)
      // console.log('focus', Editor)
      // this.editor = Editor
    },
    blur() {
      // console.log('blur')
    },
    selection(range) {
      if (range) {
        this.cursorLocation = range.index
      }
    },
    textChange(delta) {
      // console.log(delta)
    },
    imgReader(item) {
      // console.log('imgReader')
      let blob = item.getAsFile(),
        that = this
      this.reader = new FileReader()
      this.reader.onload = e => {
        this.base64 = e.target.result

        this.image = new Image()
        this.image.src = this.base64
        //this.image.id = 'img_'+ Math.random() * 10

        this.image.onload = function() {
          // 压缩图片,如果是ajax方式就先保存个高压的预览图
          let cImg = that.ajax ? compressedImg(this, 0.1) : compressedImg(this)

          // 获取图片尺寸
          // console.log((dataURLtoFile(cimg).size / 1024)/8)

          // 把压缩后的图片以base64方式保存
          // console.log('image', that.editor)
          that.editor.insertEmbed(that.cursorLocation, 'image', cImg)

          // 使用ajax方式保存
          if (that.ajax) {
            console.log(that.ajax)
            // let imgEl = document.querySelector('.ql-editor img[src="' + cImg + '"]')
            that.lock = true
            that.imgLocation = that.cursorLocation
            that.updateImg(compressedImg(this), cImg)
          }
        }
      }
      this.reader.readAsDataURL(blob)
    },
    // todo: (donkey) 测试中。。。
    updateImg(dataURL, cImg) {
      // laoding
      let imgEl = document.querySelector('.ql-editor img[src="' + cImg + '"]')
      imgEl.style = `opacity:.5`
      setTimeout(() => {
        let iEl = document.createElement('i')
        let imgSize = imgEl.getBoundingClientRect()
        // console.log(imgSize)
        iEl.className = 'el-icon-loading'
        iEl.id = 'edit_img_loading'
        iEl.style = `position:absolute; top:${imgSize.y +
          imgSize.height / 2 -
          9}px; z-index:99999; left:${imgSize.x + imgSize.width / 2 - 10}px;`
        document.body.appendChild(iEl)
      })

      // post
      let entity = {
        file: dataURLtoFile(dataURL, 'img.jpg'),
        customer_id: 'xxxx',
        data_type: '1',
        material_type: 'fuedit',
        archives_type: 'ex',
        relation_id: new Date().getTime() + ''
      }
      let formData = new FormData()
      for (let key in entity) {
        if (key === 'file') {
          formData.append('file', entity[key])
        } else {
          formData.append(key, entity[key])
        }
      }
      axios({
        url: 'http://192.200.204.14:8080/m-web/admin/file/uploadMobileFile',
        headers: { 'Content-Type': 'multipart/form-data' },
        method: 'POST',
        data: formData
      })
        .then(result => {
          let url =
            'http://192.200.204.14:8080/m-web/admin/file/files/' +
            result.data.fid +
            '.' +
            result.data.file_type
          this.editor.insertEmbed(this.imgLocation, 'image', url)
          this.editor.deleteText(this.imgLocation + 1, 1)
          this.lock = false
          // 删除loading
          let loading = document.getElementById('edit_img_loading')
          loading.parentElement.removeChild(loading)
        })
        .catch(err => {
          console.log(err)
        })
    },
    isEnv(option, value) {
      let mimeTypes = navigator.mimeTypes
      for (let mt in mimeTypes) {
        if (mimeTypes[mt][option] == value) {
          return true
        }
      }
      return false
    },
    paste(e) {
      if (this.lock) return
      let is360 = this.isEnv('type', 'application/vnd.chromium.remoting-viewer')
      if (!is360) return
      let clipboardData = e.clipboardData, //谷歌
        i = 0,
        items,
        item,
        types

      items = clipboardData.items
      if (!items) {
        return
      }
      item = items[0]
      types = clipboardData.types || []
      for (; i < types.length; i++) {
        if (types[i] === 'Files') {
          item = items[i]
          break
        }
      }
      if (item && item.kind === 'file' && item.type.match(/^image\//i)) {
        this.imgReader(item)
      }
    }
  },
  mounted() {
    this.editor = this.$refs.editor.quill

    // 监听粘贴
    document.addEventListener('paste', this.paste)
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor = null
      delete this.editor
    }
    // 清理粘贴监听
    document.removeEventListener('paste', this.paste)
  }
}
</script>
